/**
 * Created by 19610 on 2018/7/5.
 */
function Imagefactory() {
  this.file = new FileReader();
  this.form = new FormData();       //js  创建form表单
  this.request = new XMLHttpRequest();
};
Imagefactory.prototype.SetParm = function (...parm) {
  this.path = parm[0];
  this.doc = parm.length > 1 ? parm[1].target : false;
  this.fileInput = this.doc ? this.doc.files[0] : false;
  return this;
};
Imagefactory.prototype.response = function (file, request, flay) {
  if (flay == 1) {  //查詢图片
    return new Promise((res, ref) => {
      request.onreadystatechange = () => {
        if (request.status === 200 && request.readyState === 4) {
          if (request.response != '') {
            res(JSON.parse(request.response));
          } else {
            ref(JSON.parse(request.response));
          }
        }
      }
    });
  } else {//添加图片
    return new Promise((res, ref) => {
      file.onload = (e) => {
        request.onreadystatechange = () => {
          if (request.status === 200 && request.readyState === 4) {
            if (request.response != '') {
              res(JSON.parse(request.response));
            } else {
              ref(JSON.parse(request.response));
            }
          }
        }
      }
    });
  }
};

Imagefactory.prototype.create = function () {//添加
  this.request.open("POST", "http://image.myjytech.com/uploadimage");
  this.form.append('image', this.fileInput);
  this.form.append('pathname', this.path);
  this.request.send(this.form);
  this.file.readAsDataURL(this.fileInput);
  return this.response(this.file, this.request, 0);
};

Imagefactory.prototype.delete = function () { //删除
  this.request.open("get", "http://image.myjytech.com/deletedir?pathname=" + this.path);
  this.request.send(this.form);
  return this.response(this.file, this.request, 1);
};
// Imagefactory.prototype.lookuppicture = function () { //查找
//   this.request.open("get", "http://image.myjytech.com/searchimages?pathname=" + this.path);
//   this.request.send(this.form);
//   return this.response(this.file, this.request, 1);
// };

Imagefactory.prototype.edit = function () { //修改
  this.delete();
  return this.create();
};

export default Imagefactory;
